const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

/**
 * 检查并解锁用户成就的辅助函数
 */
async function checkAchievementsForUser(userId, connection) {
    try {
        // 获取用户统计数据
        const [userStats] = await connection.execute(
            `SELECT 
                u.*,
                COUNT(DISTINCT up.word_id) as words_learned
             FROM users u
             LEFT JOIN user_progress up ON u.id = up.user_id
             WHERE u.id = ?
             GROUP BY u.id`,
            [userId]
        );
        
        if (userStats.length === 0) return;
        const stats = userStats[0];
        
        // 获取所有启用的成就
        const [achievements] = await connection.execute(
            'SELECT * FROM achievements WHERE enabled = 1'
        );
        
        // 检查每个成就
        for (const achievement of achievements) {
            // 检查是否已解锁
            const [existing] = await connection.execute(
                'SELECT id FROM user_achievements WHERE user_id = ? AND achievement_id = ?',
                [userId, achievement.id]
            );
            
            if (existing.length > 0) continue; // 已解锁，跳过
            
            let shouldUnlock = false;
            let current = 0;
            
            // 根据成就类型判断是否应该解锁
            switch (achievement.type) {
                case 'learn': // 学习类成就（学习单词数）
                    current = stats.words_learned;
                    shouldUnlock = current >= achievement.target;
                    break;
                case 'words_learned':
                    current = stats.words_learned;
                    shouldUnlock = current >= achievement.target;
                    break;
                case 'continuous_days':
                    current = stats.continuous_days;
                    shouldUnlock = current >= achievement.target;
                    break;
                case 'game': // 游戏类成就（暂时跳过，需要游戏数据）
                case 'streak': // 连胜类成就（暂时跳过）
                    continue;
                default:
                    continue;
            }
            
            // 解锁成就
            if (shouldUnlock) {
                await connection.execute(
                    'INSERT INTO user_achievements (user_id, achievement_id) VALUES (?, ?)',
                    [userId, achievement.id]
                );
                console.log(`🏆 用户 ${userId} 解锁成就: ${achievement.name}`);
            }
        }
    } catch (error) {
        console.error('检查成就失败:', error);
        // 不抛出错误，避免影响主流程
    }
}
const { getGradesUpTo } = require('../utils/gradeLevel');

/**
 * 获取单词列表（根据用户年级）
 */
const getVocabulary = async (req, res) => {
    try {
        const userId = req.user.id;
        const { grade, unit, page = 1, limit = 20 } = req.query;
        
        console.log('📚 获取单词列表 - 用户ID:', userId, '是否管理员:', req.user.isAdmin, '年级:', grade);
        
        let allowedGrades = [];
        let query = '';
        let params = [];
        
        // 检查是否是管理员
        if (req.user.isAdmin) {
            // 管理员可以查看所有年级的单词
            if (grade) {
                // 如果指定了年级，只查询该年级
                query = `
                    SELECT v.*
                    FROM vocabulary v
                    WHERE v.grade = ?
                `;
                params.push(grade);
            } else {
                // 如果没有指定年级，查询所有单词
                query = `
                    SELECT v.*
                    FROM vocabulary v
                    WHERE 1=1
                `;
            }
        } else {
            // 普通用户需要userId参数
            params.push(userId);
            // 普通用户：获取用户年级
            const [users] = await db.execute('SELECT grade FROM users WHERE id = ?', [userId]);
            
            if (users.length === 0) {
                return errorResponse(res, '用户不存在', 404);
            }
            
            const userGrade = users[0].grade;
            
            // 获取该年级及之前的所有年级
            allowedGrades = getGradesUpTo(userGrade);
            
            query = `
                SELECT v.*, 
                       up.mastery_level, 
                       up.correct_count, 
                       up.wrong_count,
                       up.last_reviewed
                FROM vocabulary v
                LEFT JOIN user_progress up ON v.id = up.word_id AND up.user_id = ?
                WHERE v.grade IN (${allowedGrades.map(() => '?').join(',')})
            `;
            
            params.push(...allowedGrades);
            
            if (grade) {
                query += ' AND v.grade = ?';
                params.push(grade);
            }
        }
        
        if (unit) {
            query += ' AND v.unit = ?';
            params.push(unit);
        }
        
        query += ' ORDER BY v.id';
        
        // 计算分页 - 使用字符串拼接避免参数类型问题
        const pageNum = parseInt(page) || 1;
        const limitNum = parseInt(limit) || 20;
        const offsetNum = Math.max(0, (pageNum - 1) * limitNum);
        query += ` LIMIT ${limitNum} OFFSET ${offsetNum}`;
        
        console.log('📝 执行查询SQL:', query);
        console.log('📝 查询参数:', params);
        
        const [words] = await db.execute(query, params);
        
        console.log('✅ 查询到单词数量:', words.length);
        
        // 获取总数
        let countQuery = '';
        let countParams = [];
        
        if (req.user.isAdmin) {
            // 管理员：统计查询
            countQuery = `SELECT COUNT(*) as total FROM vocabulary v WHERE 1=1`;
            if (grade) {
                countQuery += ' AND v.grade = ?';
                countParams.push(grade);
            }
            if (unit) {
                countQuery += ' AND v.unit = ?';
                countParams.push(unit);
            }
        } else {
            // 普通用户：统计查询
            countQuery = `
                SELECT COUNT(*) as total
                FROM vocabulary v
                WHERE v.grade IN (${allowedGrades.map(() => '?').join(',')})
            `;
            countParams = [...allowedGrades];
            
            if (grade) {
                countQuery += ' AND v.grade = ?';
                countParams.push(grade);
            }
            
            if (unit) {
                countQuery += ' AND v.unit = ?';
                countParams.push(unit);
            }
        }
        
        const [countResult] = await db.execute(countQuery, countParams);
        const total = countResult[0].total;
        
        return successResponse(res, {
            words,
            pagination: {
                page: parseInt(page),
                limit: parseInt(limit),
                total,
                pages: Math.ceil(total / limit)
            }
        });
        
    } catch (error) {
        console.error('获取单词列表错误:', error);
        return errorResponse(res, '获取单词列表失败', 500, error);
    }
};

/**
 * 获取单个单词详情
 */
const getWordDetail = async (req, res) => {
    try {
        const userId = req.user.id;
        const { wordId } = req.params;
        
        const [words] = await db.execute(
            `SELECT v.*, 
                    up.mastery_level, 
                    up.correct_count, 
                    up.wrong_count,
                    up.last_reviewed,
                    up.next_review
             FROM vocabulary v
             LEFT JOIN user_progress up ON v.id = up.word_id AND up.user_id = ?
             WHERE v.id = ?`,
            [userId, wordId]
        );
        
        if (words.length === 0) {
            return errorResponse(res, '单词不存在', 404);
        }
        
        return successResponse(res, words[0]);
        
    } catch (error) {
        console.error('获取单词详情错误:', error);
        return errorResponse(res, '获取单词详情失败', 500, error);
    }
};

/**
 * 获取待复习的单词
 */
const getReviewWords = async (req, res) => {
    try {
        const userId = req.user.id;
        const { limit = 10 } = req.query;
        const limitNum = Math.min(Math.max(1, parseInt(limit) || 10), 100);
        
        const [words] = await db.execute(
            `SELECT v.*, 
                    up.mastery_level, 
                    up.correct_count, 
                    up.wrong_count,
                    up.last_reviewed,
                    up.next_review
             FROM vocabulary v
             INNER JOIN user_progress up ON v.id = up.word_id
             WHERE up.user_id = ? 
             AND up.next_review <= NOW()
             ORDER BY up.next_review ASC
             LIMIT ${limitNum}`,
            [userId]
        );
        
        return successResponse(res, words);
        
    } catch (error) {
        console.error('获取复习单词错误:', error);
        return errorResponse(res, '获取复习单词失败', 500, error);
    }
};

/**
 * 获取薄弱单词（掌握度低的）
 */
const getWeakWords = async (req, res) => {
    try {
        const userId = req.user.id;
        const { limit = 10 } = req.query;
        const limitNum = Math.min(Math.max(1, parseInt(limit) || 10), 100);
        
        const [words] = await db.execute(
            `SELECT v.*, 
                    up.mastery_level, 
                    up.correct_count, 
                    up.wrong_count,
                    up.last_reviewed
             FROM vocabulary v
             INNER JOIN user_progress up ON v.id = up.word_id
             WHERE up.user_id = ? 
             AND up.mastery_level < 60
             ORDER BY up.mastery_level ASC, up.wrong_count DESC
             LIMIT ${limitNum}`,
            [userId]
        );
        
        return successResponse(res, words);
        
    } catch (error) {
        console.error('获取薄弱单词错误:', error);
        return errorResponse(res, '获取薄弱单词失败', 500, error);
    }
};

/**
 * 记录学习/答题结果
 */
const recordAnswer = async (req, res) => {
    const connection = await db.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const userId = req.user.id;
        // 兼容两种参数格式：{ wordId, isCorrect } 和 { word_id, correct }
        const wordId = req.body.wordId || req.body.word_id;
        const isCorrect = req.body.isCorrect !== undefined ? req.body.isCorrect : req.body.correct;
        
        if (wordId === undefined || isCorrect === undefined) {
            console.error('参数错误:', req.body);
            return errorResponse(res, '缺少必要参数 (wordId/word_id 和 isCorrect/correct)', 400);
        }
        
        // 检查是否已有进度记录
        const [existing] = await connection.execute(
            'SELECT * FROM user_progress WHERE user_id = ? AND word_id = ?',
            [userId, wordId]
        );
        
        if (existing.length === 0) {
            // 创建新记录
            // 认识：初始掌握度60，5天后复习
            // 不认识：初始掌握度10，1小时后复习
            const initialMastery = isCorrect ? 60 : 10;
            const reviewInterval = isCorrect ? '5 DAY' : '1 HOUR';
            
            await connection.execute(
                `INSERT INTO user_progress (user_id, word_id, mastery_level, correct_count, wrong_count, last_reviewed, next_review, review_count)
                 VALUES (?, ?, ?, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL ${reviewInterval}), 1)`,
                [userId, wordId, initialMastery, isCorrect ? 1 : 0, isCorrect ? 0 : 1]
            );
        } else {
            // 调用存储过程更新进度和计算下次复习时间
            await connection.execute(
                'CALL calculate_next_review(?, ?, ?)',
                [userId, wordId, isCorrect]
            );
        }
        
        // 更新用户统计
        if (isCorrect) {
            await connection.execute(
                'UPDATE users SET total_correct = total_correct + 1, stars = stars + 1 WHERE id = ?',
                [userId]
            );
        } else {
            await connection.execute(
                'UPDATE users SET total_wrong = total_wrong + 1 WHERE id = ?',
                [userId]
            );
        }
        
        // 更新宠物经验值
        if (isCorrect) {
            await connection.execute(
                `UPDATE pets SET exp = exp + 10, 
                 level = FLOOR(1 + SQRT((exp + 10) / 100))
                 WHERE user_id = ?`,
                [userId]
            );
        }
        
        // 检查并解锁成就
        await checkAchievementsForUser(userId, connection);
        
        await connection.commit();
        
        // 获取更新后的进度
        const [updated] = await connection.execute(
            `SELECT up.*, v.word, v.chinese
             FROM user_progress up
             INNER JOIN vocabulary v ON up.word_id = v.id
             WHERE up.user_id = ? AND up.word_id = ?`,
            [userId, wordId]
        );
        
        return successResponse(res, updated[0], isCorrect ? '回答正确！' : '继续加油！');
        
    } catch (error) {
        await connection.rollback();
        console.error('记录答题错误:', error);
        return errorResponse(res, '记录答题失败', 500, error);
    } finally {
        connection.release();
    }
};

/**
 * 获取单词统计
 */
const getStatistics = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const [stats] = await db.execute(
            `SELECT 
                COUNT(DISTINCT up.word_id) as total_learned,
                SUM(CASE WHEN up.mastery_level >= 80 THEN 1 ELSE 0 END) as mastered,
                SUM(CASE WHEN up.mastery_level >= 60 AND up.mastery_level < 80 THEN 1 ELSE 0 END) as familiar,
                SUM(CASE WHEN up.mastery_level < 60 THEN 1 ELSE 0 END) as weak,
                AVG(up.mastery_level) as avg_mastery
             FROM user_progress up
             WHERE up.user_id = ?`,
            [userId]
        );
        
        // 获取各年级学习情况
        const [gradeStats] = await db.execute(
            `SELECT 
                v.grade,
                COUNT(DISTINCT v.id) as total_words,
                COUNT(DISTINCT up.word_id) as learned_words
             FROM vocabulary v
             LEFT JOIN user_progress up ON v.id = up.word_id AND up.user_id = ?
             GROUP BY v.grade
             ORDER BY FIELD(v.grade, '三上', '三下', '四上', '四下', '五上', '五下', '六上', '六下')`,
            [userId]
        );
        
        return successResponse(res, {
            overall: stats[0],
            byGrade: gradeStats
        });
        
    } catch (error) {
        console.error('获取统计信息错误:', error);
        return errorResponse(res, '获取统计信息失败', 500, error);
    }
};

/**
 * 获取待学习的单词（新单词优先）
 */
const getWordsToLearn = async (req, res) => {
    try {
        const userId = req.user.id;
        const { limit = 10 } = req.query;
        
        // 获取用户年级
        const [users] = await db.execute(
            'SELECT grade FROM users WHERE id = ?',
            [userId]
        );
        
        if (users.length === 0) {
            return errorResponse(res, '用户不存在', 404);
        }
        
        const userGrade = users[0].grade;
        
        // 获取该年级及之前的所有年级
        const { getGradesUpTo } = require('../utils/gradeLevel');
        const allowedGrades = getGradesUpTo(userGrade);
        
        console.log('用户年级:', userGrade);
        console.log('允许的年级:', allowedGrades);
        
        if (allowedGrades.length === 0) {
            return successResponse(res, []);
        }
        
        // 生成占位符
        const placeholders = allowedGrades.map(() => '?').join(',');
        const limitNum = Math.min(Math.max(1, parseInt(limit) || 10), 100); // 限制在1-100之间
        
        console.log('占位符:', placeholders);
        console.log('参数数组:', [userId, ...allowedGrades]);
        console.log('LIMIT值:', limitNum);
        
        // 获取该年级及之前的单词，优先显示未学习和掌握度低的
        // 注意：LIMIT使用字符串拼接，不使用占位符，因为MySQL预处理语句对LIMIT有限制
        const sql = `SELECT v.*, 
                    COALESCE(up.mastery_level, 0) as mastery_level,
                    COALESCE(up.correct_count, 0) as correct_count,
                    COALESCE(up.wrong_count, 0) as wrong_count
             FROM vocabulary v
             LEFT JOIN user_progress up ON v.id = up.word_id AND up.user_id = ?
             WHERE v.grade IN (${placeholders})
             AND (up.mastery_level IS NULL OR up.mastery_level < 80)
             ORDER BY 
                CASE 
                    WHEN up.mastery_level IS NULL THEN 0
                    WHEN up.next_review IS NOT NULL AND up.next_review <= NOW() THEN 1
                    ELSE 2
                END,
                RAND()
             LIMIT ${limitNum}`;
        
        console.log('最终SQL:', sql);
        
        const [words] = await db.execute(
            sql,
            [userId, ...allowedGrades]
        );
        
        return successResponse(res, words);
        
    } catch (error) {
        console.error('获取待学习单词错误:', error);
        return errorResponse(res, '获取失败', 500, error);
    }
};

module.exports = {
    getVocabulary,
    getWordDetail,
    getReviewWords,
    getWeakWords,
    recordAnswer,
    getStatistics,
    getWordsToLearn
};

